<template>
  <u-popup v-if="show" v-model="show" :mask="true" mode="bottom" @close="bindClose()">
    <div class="preview-content">
      <div class="title">保存</div>
      <div class="wrap-content">
        <wd-swiper v-model:current="current"
                   :imageMode="'aspectFit'"
                   :autoplay="false" :height="124" :indicator="{ type: 'dots-bar' }" :list="list" text-key="title" value-key="url"></wd-swiper>
      </div>

      <div style="border-top: 1px solid #e4e4e4"></div>
      <u-form ref="uFormRef" :label-width="'auto'" :model="form">
        <u-form-item label="设计名称: ">
          <u-input v-model="form.productTitle" />
        </u-form-item>
        <u-form-item>
          <u-input v-model="form.productDescription" placeholder="添加作品描述..." type="textarea" />
        </u-form-item>
        <u-form-item>
          <div class="keyword-label"># 关键词</div>
          <div class="keyword-ul">
            <div v-for="(item, index) in keywordList" :key="index" class="keyword-li">
              <div :class="{ active: form.productKeywords.includes(item) }" class="keyword-tag" @click="bindKeyword(item)">{{ item }}</div>
            </div>
          </div>
        </u-form-item>
      </u-form>
      <div class="btns">
        <div class="btn save-btn" @click="bindSave">保存</div>
      </div>
    </div>
  </u-popup>
</template>

<script lang="ts" setup>
import { ref, shallowRef, toRaw } from 'vue';
import { useDesignerGoodState } from '@/state/modules/DesignerGoodState';
import { createBase64, saveProductApi } from "@/api/designApi";
import { getSearchKeyword } from "@/api/store";

const form = ref({
  productTitle: '',
  productDescription: '',
  productKeywords: [],
});

// {
//   image: 'https://cdn.uviewpro.cn/uview/xxx.png',
//     title: '昨夜星辰昨夜风，画楼西畔桂堂东',
// },
const list = shallowRef<any[]>([

]);
const useDesignerGood = useDesignerGoodState();

const bindKeyword = (item) => {
  console.log({ item }, form.value.productKeywords);
  if (form.value.productKeywords?.includes(item)) {
    form.value.productKeywords = form.value.productKeywords.filter((i) => i !== item);
  } else {
    form.value.productKeywords.push(item);
  }
};

const bindSave = async () => {
  uni.showLoading({ title: '保存中...',  mask: true })
  console.log('保存', useDesignerGood.towardPositionArr, useDesignerGood.getActiveGood);
  console.log('保存', useDesignerGood.activePosition, useDesignerGood.bodyPositionIndex)

  const workData = '';
  // toRaw(useDesignerGood.towardPositionArr).map((item) => {
  //   return {
  //     ...item,
  //     AICanvas: undefined,
  //     aiData: {
  //       bgColor: item.AICanvas?.bgColor,
  //       // fixme
  //       allNodeData: item.AICanvas?.allNodeObject,
  //     },
  //   };
  // });

  //list.value.map((item) => item.image)
  const images = [];
  for(let item of list.value) {
    console.log(item)
    if(item.url) {
      const imgUrl = await createBase64({base64: item.url})
      images.push({ image: imgUrl.data.link, title: item.title})
    }else {
      uni.hideLoading();
      uni.showToast({
        title: item.title + '未设计',
        icon: 'error',
      });
      return;
    }
  }

  console.log('workData', workData)
  const data = {
    designAreaData: JSON.stringify(images),
    designPrice: 0,
    id: useDesignerGood.getActiveGood.id,
    mergeTheCoverImage: images.map(item => item.image).join(','),
    productDescription: form.value.productDescription,
    productKeywords: form.value.productKeywords.join(','),
    productTitle: form.value.productTitle,
    workData: JSON.stringify(workData),
    skuColor:useDesignerGood.activePosition?.skuColorName
  };
  saveProductApi(data).then((res) => {
    console.log(res);
    uni.hideLoading();
    uni.showToast({
      title: '保存成功',
      icon: 'success',
    });
    show.value = false;
    uni.reLaunch({ url: '/subPage/design/me/me' })
  }).catch((err) => {
    console.error('保存设计', err)
    uni.hideLoading();
    uni.showToast({
      title: '保存失败',
      icon: 'success',
    });
  })
    .finally(() => {
  });
};

const show = ref(false);
const open = async () => {
  // console.log('预览', useDesignerGood.towardPositionArr);
  await uni.showLoading({ title: '加载中...' });
  const arr = [];
  for (let i = 0; i < useDesignerGood.towardPositionArr.length; i++) {
    const item = toRaw(useDesignerGood.towardPositionArr)[i];
    arr.push({
      url: await item.AICanvas?.toImageData(),
      title: item.name,
    });
  }
  console.log({ arr });
  list.value = arr;
  uni.hideLoading();
  show.value = true;
};
const bindClose = () => {
  show.value = false;
};

const keywordList = shallowRef([])
function initKeyword() {
  getSearchKeyword().then(res => {
    keywordList.value = res.data
  })
}
initKeyword()

defineExpose({
  open,
});
</script>
<style lang="scss" scoped>
.preview-content {
  background: #ffffff;
  border-radius: 16rpx 16rpx 16rpx 16rpx;
  padding: 32rpx;

  .title {
    width: 132rpx;
    height: 42rpx;
    font-weight: bold;
    font-size: 32rpx;
    color: #222222;
    line-height: 42rpx;
    text-align: center;
    margin: 0 auto;
  }

  .wrap-content {
    padding: 24rpx 16rpx 48rpx;
  }

  .btns {
    display: flex;
    align-items: center;
    justify-content: space-between;

    .btn {
      width: 100%;
      height: 72rpx;
      background: #f3f7f8;
      border-radius: 4rpx 4rpx 4rpx 4rpx;
      font-weight: 400;
      font-size: 28rpx;
      color: #6f6f6f;
      line-height: 72rpx;
      text-align: center;

      &.save-btn {
        background: #f25a27;
        color: #ffffff;
      }
    }
  }
}

.wrap {
  padding: 40rpx;
  background: red;
}

.keyword-label {
  width: 144rpx;
  height: 54rpx;
  font-weight: 400;
  font-size: 28rpx;
  color: #222222;
  line-height: 54rpx;
  padding: 0 16rpx;
  background: #f3f7f8;
  border-radius: 28rpx 28rpx 28rpx 28rpx;
  margin-bottom: 16rpx;
}

.keyword-ul {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 16rpx;

  .keyword-li {
    .keyword-tag {
      height: 54rpx;
      font-size: 28rpx;
      color: #666666;
      line-height: 54rpx;
      text-align: center;
      padding: 0 16rpx;
      background: #f3f7f8;
      border-radius: 28rpx 28rpx 28rpx 28rpx;

      &.active {
        color: #ffffff;
        background: linear-gradient(90deg, #f32f1a 0%, #f68a2d 100%);
      }
    }
  }
}

.wrap-content :deep(.u-swiper-image) {
  height: 248rpx;
}
</style>
<style scoped>
.wrap-content :deep(.u-swiper-image) {
  border: 1px solid blue;
}
</style>
